package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntityAdvCost;
import com.loongtech.bi.entity.system.EntityAdvDefaultConfig;
import com.loongtech.bi.manager.system.AdvCostManager;
import com.loongtech.bi.manager.system.AdvDefaultManager;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.core.util.Utils;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * 
 * ClassName: AdvConfigAction
 * 
 * @Description: TODO 广告配置
 * @author liuchen
 * @date 2016-11-14 下午5:04:18
 */
@Controller("advCostAction")
@Scope("view")
public class AdvCostAction {

	private final String tmpuploaddir = "/usr/local/tomcat/upload/";

	@Autowired
	private AdvCostManager managerBase;

	@Autowired
	private AdvDefaultManager managerDefaultBase;

	private int uploadparamtype;
	private static File file;
	private Map<String, Integer> queryGameParamTypeItmes;

	private List<EntityAdvCost> list;

	private EntityAdvCost entity;

	private EntityAdvDefaultConfig advDefault;

	@Autowired
	public void init() {
		initData();
	}

	private void initData() {
		entity = new EntityAdvCost();
		search();
		searchDelfault();
	}

	public void searchDelfault() {
		StringBuffer hql = new StringBuffer(" from EntityAdvDefaultConfig l where 1=1 ");
		advDefault = managerBase.getByQuery(hql.toString(), new Object[] {});
		if (advDefault == null) {
			advDefault = new EntityAdvDefaultConfig();
		}
	}

	public void search() {
		List<Object> cons = new ArrayList<Object>();
		StringBuffer hql = new StringBuffer(" from EntityAdvCost l where 1=1 ");
		if (!Utils.isEmptyStr(entity.getLdate())) {
			hql.append(" and l.ldate = ? ");
			cons.add(entity.getLdate());
		}
		if (!Utils.isEmptyStr(entity.getPlatform())) {
			hql.append(" and l.platform = ? ");
			cons.add(entity.getPlatform());
		}
		if (!Utils.isEmptyStr(entity.getAgent())) {
			hql.append(" and l.agent = ? ");
			cons.add(entity.getAgent());
		}
		if (!Utils.isEmptyStr(entity.getChannelName())) {
			hql.append(" and l.channelName = ? ");
			cons.add(entity.getChannelName());
		}
		if (!Utils.isEmptyStr(entity.getCost())) {
			hql.append(" and l.cost = ? ");
			cons.add(entity.getCost());
		}
		if (!Utils.isEmptyStr(entity.getRebate())) {
			hql.append(" and l.rebate = ? ");
			cons.add(entity.getRebate());
		}
		if (!Utils.isEmptyStr(entity.getDiscount())) {
			hql.append(" and l.discount = ? ");
			cons.add(entity.getDiscount());
		}
		if (!Utils.isEmptyStr(entity.getRoi())) {
			hql.append(" and l.roi = ? ");
			cons.add(entity.getRoi());
		}
		list = managerBase.findByQuery(hql.toString(), cons.toArray());
	}

	public void updateDefault(EntityAdvDefaultConfig e) {
		FacesContext context = FacesContext.getCurrentInstance();
		if (validate(context, e)) {
			managerDefaultBase.merge(e);
			context.addMessage(null, new FacesMessage("修改成功！"));
			initData();
		}
	}

	private boolean validate(FacesContext context, EntityAdvDefaultConfig ebp) {

		if (Utils.isEmptyStr(ebp.getIosRoi())) {
			context.addMessage(null, new FacesMessage("IOS分成比例不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getAndroidRoi())) {
			context.addMessage(null, new FacesMessage("安卓分成比例不能为空！"));
			return false;
		}
		return true;
	}

	public void add() {
		FacesContext context = FacesContext.getCurrentInstance();
		if (validate(context, entity)) {
			managerBase.persist(entity);
			context.addMessage(null, new FacesMessage("添加成功！"));
			initData();
		}
	}

	public void modify(EntityAdvCost e) {
		FacesContext context = FacesContext.getCurrentInstance();
		if (validate(context, e)) {
			managerBase.merge(e);
			context.addMessage(null, new FacesMessage("修改成功！"));
			initData();
		}
	}

	public void delete(int id) {
		FacesContext context = FacesContext.getCurrentInstance();
		if (!Utils.isEmptyStr(String.valueOf(id))) {
			managerBase.removeById(id);
		}
		context.addMessage(null, new FacesMessage("删除成功！"));
		initData();
	}

	public void upload(FileUploadEvent event) throws IOException {
		System.out.println("upload file: ");
		UploadedFile ufile = event.getFile();
		if (ufile != null) {
			InputStream inputStream = ufile.getInputstream();

			File tmpdir = new File(tmpuploaddir);
			if (!tmpdir.exists()) {
				tmpdir.mkdir();
			}
			file = new File(tmpuploaddir + ufile.getFileName() + System.currentTimeMillis());
			file.createNewFile();

			OutputStream outputStream = new FileOutputStream(file);
			byte[] b = new byte[1024];
			while ((inputStream.read(b)) != -1) {
				outputStream.write(b);
			}
			inputStream.close();
			outputStream.close();
		}

		System.out.println("上传了文件：" + file == null ? file : file.getAbsolutePath());
	}

	public List<EntityAdvCost> parseUploadedExcel(File file) throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();
		List<EntityAdvCost> result = new ArrayList<EntityAdvCost>();
		InputStream input = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(input);
		Sheet tempSheet = wb.getSheetAt(0);
		if (tempSheet == null) {
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "数据错误！"));
			IOUtils.closeQuietly(input);

			return result;
		}
		int rowNum = tempSheet.getLastRowNum();// 获得总行数
		for (int i = 0; i <= rowNum; i++) {
			Row row = tempSheet.getRow(i);
			if (row == null) {
				continue;
			}
			String ldate = ExcelUtils.getCellValue(row.getCell(0));
			String platform = ExcelUtils.getCellValue(row.getCell(1));
			String agent = ExcelUtils.getCellValue(row.getCell(2));
			String channelName = ExcelUtils.getCellValue(row.getCell(3));
			String cost = ExcelUtils.getCellValue(row.getCell(4));
			String rebate = ExcelUtils.getCellValue(row.getCell(5));
			String discount = ExcelUtils.getCellValue(row.getCell(6));
			String roi = ExcelUtils.getCellValue(row.getCell(7));

			if ("".equals(ldate) || "".equals(cost) || "".equals(channelName) || "".equals(agent)
					|| "".equals(platform) || "".equals(discount) || "".equals(roi) || "".equals(rebate)) {
				continue;
			}

			EntityAdvCost e = new EntityAdvCost();
			e.setLdate(ldate);
			e.setPlatform(platform);
			e.setAgent(agent);
			e.setChannelName(channelName);
			e.setCost(cost);
			e.setRebate(rebate);
			e.setDiscount(discount);
			e.setRoi(roi);
			result.add(e);
		}
		IOUtils.closeQuietly(input);
		return result;
	}

	public void parseExcel() {
		FacesContext context = FacesContext.getCurrentInstance();
		if (file != null && file.exists()) {
			try {
				List<EntityAdvCost> tmp = parseUploadedExcel(file);
				if (tmp != null && tmp.size() > 0) {
					for (EntityAdvCost e : tmp) {
						managerBase.persist(e);
					}
					initData();
					context.addMessage(null, new FacesMessage("解析成功！"));
				}
			} catch (Exception e) {
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "解析文件错误！"));
				e.printStackTrace();
			} finally {
				if (file != null && file.exists()) {
					file.delete();
				}
			}
		} else {
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "请上传文件！"));
			return;
		}
	}

	private boolean validate(FacesContext context, EntityAdvCost ebp) {
		if (Utils.isEmptyStr(ebp.getLdate())) {
			context.addMessage(null, new FacesMessage("日期不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getPlatform()) || "0".equals(ebp.getPlatform())) {
			context.addMessage(null, new FacesMessage("渠道平台不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getAgent())) {
			context.addMessage(null, new FacesMessage("代理公司不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getChannelName())) {
			context.addMessage(null, new FacesMessage("渠道名称不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getCost())) {
			context.addMessage(null, new FacesMessage("成本不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getRebate())) {
			context.addMessage(null, new FacesMessage("返点不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getDiscount())) {
			context.addMessage(null, new FacesMessage("折后成本不能为空！"));
			return false;
		}
		if (Utils.isEmptyStr(ebp.getRoi())) {
			context.addMessage(null, new FacesMessage("分成比例不能为空！"));
			return false;
		}
		return true;
	}

	public EntityAdvCost getEntity() {
		return entity;
	}

	public void setEntity(EntityAdvCost entity) {
		this.entity = entity;
	}

	public EntityAdvDefaultConfig getAdvDefault() {
		return advDefault;
	}

	public void setAdvDefault(EntityAdvDefaultConfig advDefault) {
		this.advDefault = advDefault;
	}

	public List<EntityAdvCost> getList() {
		return list;
	}

	public void setList(List<EntityAdvCost> list) {
		this.list = list;
	}

	public int getUploadparamtype() {
		return uploadparamtype;
	}

	public void setUploadparamtype(int uploadparamtype) {
		this.uploadparamtype = uploadparamtype;
	}

	public static File getFile() {
		return file;
	}

	public static void setFile(File file) {
		AdvCostAction.file = file;
	}

	public Map<String, Integer> getQueryGameParamTypeItmes() {
		return queryGameParamTypeItmes;
	}

	public void setQueryGameParamTypeItmes(Map<String, Integer> queryGameParamTypeItmes) {
		this.queryGameParamTypeItmes = queryGameParamTypeItmes;
	}
}
